#include "chap10.h"
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {
	char *phrase = argv[1];
	char *vars[] = {"RSS_FEED=http://rss.cnn.com/rss/edition.rss", NULL};
	int fd[2];
	if (pipe(fd) == -1) {
		error("Can't create the pipe");
	}
/*	FILE *f = fopen("stories.txt", "w");
	if (!f) {
		error("Can't open stories.txt");
	}
*/
	pid_t pid = fork();
	if (pid == -1) {
		error("Can't fork process");
	}

	if (!pid) {
		close(fd[0]);
		if (dup2(fd[1], 1) == -1) {
			error("Can't redirect Standard Output");
		}
		if (execle("/usr/bin/python", "usr/bin/python", "./rssgossip.py", "-u", phrase, NULL, vars) == -1) {
			error("Can't run script");
		}
	}

	close(fd[1]);
	if (dup2(fd[0],0) == -1) {
		error("Can't redirect Standard input");
	}
	char line[255];
	while (fgets(line, 255, stdin)) {
		if (line[0] == '\t') {
			open_url(line + 1);
		}
	}
	int pid_status;
	if (waitpid(pid, &pid_status, 0) == -1) {
		error("Error waiting for child process");
	}
	if (WEXITSTATUS(pid_status)) {
		puts("Error Status non-zero");
	}
	return 0;
}

